﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ProgNetComponents.Design.Editors
{
    /// <summary>
    /// Allows to select multiple results from list of availavle choices
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseMultiSelectListEditor<T> : BaseListEditor
    {
        protected override System.Windows.Forms.ListBox CreateControl()
        {
            CheckedListBox l= new System.Windows.Forms.CheckedListBox();
            l.CheckOnClick = true;
            return l;
        }
        protected override object GetSelectedValue()
        {
            List<T> list = new List<T>();
            string key ;
            for (int i=0; i < _ListBox.Items.Count; i++)
            {
                if ((_ListBox as CheckedListBox).GetItemChecked(i))
                {
                    key = _ListBox.Items[i].AsString();
                    if (_List.ContainsKey(key))
                    {
                        if (!list.Contains((T)_List[key]))
                        {
                            list.Add((T)_List[key]);
                        }
                    }
                }
            }
            return list.ToArray();
        }
        protected override void SetSelectedItems(object value)
        {
            T[] t = null;
            if (value != null && value is T[])
            {
                t = value as T[];
            }

            for (int i=0; i < _ListBox.Items.Count; i++)
            {
                string key = _ListBox.Items[i].AsString();
                if (t!=null && _List.ContainsKey(key))
                {
                    (_ListBox as CheckedListBox).SetItemChecked(i, t.Contains((T)_List[key]));
                }
            }
        }
    }
}
